'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { useSession } from 'next-auth/react'
import Button from '@/components/ui/Button'
import { toast } from 'react-hot-toast'

export default function EditAnnouncementPage() {
  const router = useRouter()
  const params = useParams()
  const announcementId = params?.id as string | undefined;

  const { data: session, status } = useSession()
  
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [originalExperimentId, setOriginalExperimentId] = useState<string | null>(null);
  const [loading, setLoading] = useState(false)
  const [pageLoading, setPageLoading] = useState(true) // 用于初始数据加载
  const [error, setError] = useState('')

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.replace('/login')
      return;
    }

    if (status === 'authenticated' && announcementId) {
      if (session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER') {
        toast.error('您没有权限编辑公告')
        router.replace('/')
        return;
      }

      const fetchAnnouncement = async () => {
        setPageLoading(true);
        try {
          const res = await fetch(`/api/announcements/${announcementId}`)
          if (!res.ok) {
            if (res.status === 404) {
              throw new Error('公告未找到')
            } else if (res.status === 403) {
                 const errData = await res.json();
                 throw new Error(errData.message || '您没有权限编辑此公告');
            } 
            throw new Error('获取公告详情失败')
          }
          const data = await res.json();
          if (data.announcement) {
            setTitle(data.announcement.title)
            setContent(data.announcement.content)
            setOriginalExperimentId(data.announcement.experimentId);
            // 后端API /api/announcements/[id] GET 请求应该包含权限检查
            // 如果需要，可以在这里再次验证用户是否有权限编辑这个特定公告
            // 例如：data.announcement.experiment?.createdById === session.user.id || session.user.role === 'ADMIN'
          } else {
            throw new Error('公告数据格式不正确')
          }
        } catch (err: any) {
          toast.error(err.message || '无法加载公告信息')
          setError(err.message)
          // 如果因权限或找不到公告而报错，可能需要重定向
          // router.replace('/'); // 或者到实验详情页
        } finally {
          setPageLoading(false);
        }
      };
      fetchAnnouncement();
    }
  }, [session, status, router, announcementId])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!title.trim() || !content.trim()) {
      setError('标题和内容不能为空')
      return
    }
    if (!announcementId) {
        setError('公告ID缺失，无法更新');
        toast.error('公告ID缺失');
        return;
    }

    setLoading(true)
    setError('')

    try {
      const response = await fetch(`/api/announcements/${announcementId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title,
          content,
        }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '更新公告失败')
      }

      toast.success('公告更新成功！')
      // 导航回实验详情页或公告列表，需要 experimentId
      if (originalExperimentId) {
        router.push(`/experiments/${originalExperimentId}`); 
      } else {
        router.push('/') // Fallback to homepage
      }
    } catch (err: any) {
      setError(err.message || '更新公告失败，请稍后重试')
      toast.error(err.message || '更新公告失败')
    } finally {
      setLoading(false)
    }
  }

  if (status === 'loading' || pageLoading) {
    return <div className="flex justify-center items-center min-h-screen">加载中...</div>
  }
  
  if (status === 'unauthenticated' || (session && session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER')) {
    // useEffect应该已处理重定向，但作为安全措施
    return <div className="flex justify-center items-center min-h-screen">无权访问</div>;
  }

  if (error && !title && !content) { // 如果在加载数据时发生严重错误，显示错误信息
    return (
        <div className="min-h-screen bg-gray-100 py-8 px-4 sm:px-6 lg:px-8">
            <div className="max-w-2xl mx-auto text-center">
                 <h1 className="text-3xl font-bold text-gray-900 mb-6">错误</h1>
                 <p className="text-red-600">{error}</p>
                 <Button onClick={() => router.back()} className="mt-4">返回</Button>
            </div>
        </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100 py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-2xl mx-auto">
        <h1 className="text-3xl font-bold text-gray-900 mb-6 text-center">编辑公告</h1>
        
        {error && !loading && (
          <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
            {error} {/* Display errors that occur during submit, but not initial load error if form is still usable */}
          </div>
        )}

        <form onSubmit={handleSubmit} className="bg-white shadow-md rounded-lg p-8 space-y-6">
          <div>
            <label htmlFor="title" className="block text-sm font-medium text-gray-700">
              公告标题 <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              id="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm p-2"
              required
            />
          </div>

          <div>
            <label htmlFor="content" className="block text-sm font-medium text-gray-700">
              公告内容 <span className="text-red-500">*</span>
            </label>
            <textarea
              id="content"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              rows={10}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm p-2"
              required
            />
          </div>
          
          <div className="flex justify-end space-x-3">
            <Button type="button" variant="secondary" onClick={() => router.back()} disabled={loading}>
              取消
            </Button>
            <Button type="submit" variant="primary" disabled={loading}>
              {loading ? '更新中...' : '确认更新'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
} 